package com.gph.saviorframework.auth;

import com.alibaba.fastjson.JSONObject;
import com.gph.saviorframework.auth.sec.rsa.RsaUtils;
import com.gph.saviorframework.auth.service.AuthCheckService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class RequestCheckContract {

    @Value("${key}")
    private String key;

    @Value("${name}")
    private String name;

    @Autowired
    private AuthCheckService authService;


    @Before("within(@org.springframework.stereotype.Controller *) && @annotation(check)")
    public void requestCheck(JoinPoint joinPoint,AuthLimit check)
            throws RequestCheckException{
        HttpServletRequest request = null;
        String userName = "";

        Object[] args = joinPoint.getArgs();
        for(int i=0;i<args.length;i++){
            if(args[i] instanceof HttpServletRequest){
                request = (HttpServletRequest)args[i];
                if(request.getSession().getAttribute("_USERNAME_")==null){
                    throw new RequestCheckException("用户未登录");
                }
                userName = request.getSession().getAttribute("_USERNAME_").toString();

                break;
            }
        }

        if(request == null){
            throw new RequestCheckException("参数中缺失HttpServletRequest参数");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",userName);
        jsonObject.put("sysCode",name);
        jsonObject.put("reqTime",Long.valueOf(new Date().getTime()));
        jsonObject.put("serviceName",check.service());

        String sign = "";

        try{
            sign = RsaUtils.sign(jsonObject.toJSONString().getBytes(),key);
        }
        catch (Exception ex){
            ex.printStackTrace();
        }

        JSONObject obj = JSONObject.parseObject(authService.checkAuth(userName, name, jsonObject.getString("reqTime"), check.service(), sign));

        if(obj.getString("access").equals("N")){
            throw new RequestCheckException("无权限访问");
        }
    }
}
